<template>
  <!--
    切换下布局就好了
  -->
    <div style="height: 100%;text-align: left;font-family: Consolas;padding: 0 ;margin: 0;outline-style: none;background-color:#f9f9f9" class="no_bar" >
        <el-container style="height: 100%;width: 100%">
            <el-header style="height: 12%;min-height: 140px;overflow: hidden">
                <div style="height: 100%">
                    <div style="padding: 8px 0px 0px 0px">
                        <el-input v-model="host" style="width: 180px" size="small" placeholder="地址">地址</el-input>
                        <el-input v-model="port" style="width: 180px;margin-left: 12px" size="small" placeholder="端口">端口</el-input>
                        <el-input v-model="password" style="width: 180px;margin-left: 12px" size="small" type="password" placeholder="密码">密码</el-input>
                        <el-button @click="login" style="margin-left: 12px" size="small">登录</el-button>

                        <el-input v-model="serializeUrl" style="width: 260px;margin-left: 12px" size="small"
                                  placeholder="序列化地址"></el-input>
                    </div>
                    <div style="padding: 8px 0px 0px 0px; margin-top:8px">
                        <el-button size="small" @click="delete0" style="">删除</el-button>
                        <el-button size="small" @click="reload0" style="margin-left: 12px">刷新</el-button>

                        <el-button size="small" @click="runCmd" style="margin-left: 12px">run</el-button>
                    </div>

                    <div style="padding: 8px 0px 0px 0px; margin-top:8px">
                        <el-checkbox v-model="serialize" style="" @change="saveConfig">java反序列化</el-checkbox>
                        <el-checkbox v-model="jsonFormat_" style="margin-left: 12px" @change="saveConfig">json格式化</el-checkbox>
                        <el-checkbox v-model="showChild_" style="margin-left: 12px" @change="saveConfig">是否展开</el-checkbox>
                        <span style="margin-left: 12px">{{currentKey}}</span>
                    </div>
                </div>
            </el-header>

            <el-main style="height: 88%">
              <div style="display: flex;height: 100%;flex-wrap: wrap">
                <div style="height: 50%;width: 100%">
                  <!--头部-->
                  <div class="common_box" style="margin-right: 12px;position: relative">
                    <div style="position: fixed">
                      <el-input v-model="search" placeholder="搜索" style="width:90%;margin-right: 8px;padding: 8px" size="small" @change="query"></el-input>
                    </div>

                    <div style="margin-top: 48px;height: calc(100% - 50px);overflow: scroll" class="no_bar">
                      <div v-if="v.array.length > 0" v-for="(v,k) in keys" style="font-size: 14px;cursor: pointer;text-align: left;margin-left: 4px;">
                        <div style="margin: 4px" class="select_01">
                          <el-checkbox :indeterminate="v.indeterminate" v-model="v.select"
                                       @change="parentChange(v)"></el-checkbox>
                          <span @click="v.showChild = !v.showChild;currentKey=k" style="margin-left: 8px;display: inline-block">{{k}}</span>
                        </div>
                        <!--子选项 -->
                        <el-collapse-transition>
                          <div v-if="v.showChild">
                            <div v-for="y in v.array" style="margin-left: 16px;padding: 4px;" class="select_01" @click="currentKey=y.value">
                              <el-checkbox v-model="y.select" @change="childChange(v,y)"></el-checkbox>
                              <span @click="detail(y);leftSelectObj=y" style="margin-left: 8px;display: inline-block" :class="{select_02:leftSelectObj==y}">{{y.name}}</span>
                              <a-tag color="green" style="margin-left: 8px" v-if="'string' == y.type">
                                {{y.type}}
                              </a-tag>
                              <a-tag color="orange" style="margin-left: 8px" v-if="'hash' == y.type">
                                {{y.type}}
                              </a-tag>
                            </div>
                          </div>
                        </el-collapse-transition>
                      </div>
                    </div>
                  </div>
                </div>

                <div style="height: 50%;display: flex;width: 100%;padding-top: 8px">
                  <!--下面两栏-->
                  <div style="height: 100%;width: 35%">
                    <div  class="input_box" id="redis_cmd" contenteditable="true" v-on:keydown.alt.enter="runCmd"></div>
                  </div>
                  <div style="height: 100%;width: 65%">
                    <pre style="font-family: 'Yu Gothic UI';width: 100%;" class="no_bar common_box">{{showMsg}}</pre>
                  </div>
                </div>
              </div>
            </el-main>
        </el-container>
    </div>
</template>

<script>
import http from "../../base/http"
    export default {
        data() {
            return {
                host: 'redis.wsdchigh.top',
                port: 6900,
                password: '',
                search: '',
                keys: [],
                showMsg: "11111",
                jsonFormat_: true,
                serialize: false,
                serializeUrl: '',
                cmd: '',


                showChild_:false,
                //  如果是选中了 使用这个进行标记  颜色突出
                leftSelectObj:null,
                //  记录鼠标当前悬浮的key
                currentKey:'',

                cmd1:""
            }
        },

        created() {
            //  从本地加载配置信息
            let config = this.$cache.getCommon("redis_console");
            if(config != null){
                let parse = JSON.parse(config);
                this.jsonFormat_ = parse.jsonFormat_;
                this.serialize = parse.serialize;
                this.serializeUrl = parse.serializeUrl;
                this.host = parse.host;
                this.port = parse.port;
                this.password = parse.password;
                this.showChild_ = parse.showChild_;
            }
            let that = this;
            this.$event.register("RedisConsole.vue", {
                listen: ["RedisConsole.vue?api=loginRedisConsole",
                    "RedisConsole.vue?api=query",
                    "RedisConsole.vue?api=getByKey",
                    "RedisConsole.vue?api=redisCmdLine",
                    "RedisConsole.vue?api=redisKeyDetailAndSerialize"
                ],
                callback(res) {
                    //  console.log(res)
                    switch (res.type) {
                        case "RedisConsole.vue?api=loginRedisConsole": {
                            if (res.data.status == 200) {
                                let token = res.data.data.data;
                                that.$token = token;
                                //    查询key
                                that.query()
                            } else {

                            }
                        }
                            break;

                        case "RedisConsole.vue?api=query": {
                            if (res.data.status == 200) {
                                let keys_ = res.data.data.data;
                                let keys_1 = [];
                                for(let x of keys_){
                                  keys_1.push({
                                    key:x
                                  })
                                }
                                let keysResult = {};

                                var getText_ = (str,max) => {
                                    let rtn = "";
                                    if(str.length >= max){
                                        rtn = "..."+str.substring(str.length-max,str.length)
                                        return rtn;
                                    }else{
                                        return str;
                                    }
                                }

                                let max = 100;
                                keys_1.forEach(k => {
                                  //  k {key:key,type:type}
                                    let index = k.key.search("::");
                                    if (index != -1) {
                                        let head = getText_(k.key.substring(0, index),max);
                                        let tail = k.key.substring(index, k.key.length)
                                        if (keysResult[head] == null) {
                                            keysResult[head] = {
                                                array: []
                                            };
                                        }

                                        keysResult[head].array.push({
                                            name: getText_(tail,max),
                                            value: k.key,
                                            select: false,
                                            type:k.type,
                                        });

                                        if (keysResult[head].select == null) {
                                            //  父节点是否选中
                                            keysResult[head].select = false;
                                            //  父节点是否为 半选
                                            keysResult[head].indeterminate = false;
                                            //  是否展示所有子节点
                                            keysResult[head].showChild = that.showChild_
                                        }
                                    } else {
                                        let k1 = getText_(k.key,max)
                                        keysResult[k1] = {
                                            array: [{
                                                name: k1,
                                                value: k.key,
                                                select: false,
                                                type:k.type
                                            }],
                                            select: false,
                                            indeterminate: false,
                                            showChild: that.showChild_
                                        }
                                    }
                                })
                                that.keys = keysResult;
                            }
                        }

                            break;

                        case "RedisConsole.vue?api=getByKey": {
                            if (res.data.status == 200) {
                                if (that.jsonFormat_) {

                                    if(res.data.data.data.type == 'string'){
                                      that.showMsg = that.jsonFormat(res.data.data.data.value);
                                    }else if (res.data.data.data.type ==  'hash'){
                                      that.showMsg = that.jsonFormat(res.data.data.data.valueList);
                                    }


                                } else {
                                    that.showMsg = res.data.data.data;
                                }
                            }
                        }

                            break;

                        case "RedisConsole.vue?api=redisKeyDetailAndSerialize":
                        {
                            if (res.data.status == 200) {
                                if (that.jsonFormat_) {
                                    that.showMsg = that.jsonFormat(res.data.data.data)
                                } else {
                                    that.showMsg = res.data.data.data;
                                }
                            }
                        }
                            break;


                        case "RedisConsole.vue?api=redisCmdLine":
                        {
                            if(res.data.status == 200){
                                if (that.jsonFormat_) {
                                    that.showMsg = that.jsonFormat(res.data.data.data)
                                } else {
                                    that.showMsg = res.data.data.data;
                                }
                            }
                        }
                            break;

                    }
                }
            })
        },

        methods: {
            login() {
                let data = {
                    host: this.host,
                    port: this.port,
                    password: this.password
                };
                http.loginRedisConsole(data, "RedisConsole.vue?api=loginRedisConsole");
            },

            query() {
                let data = {
                    token: this.$token,
                    query: this.search
                };

                http.redisKeys(data, "RedisConsole.vue?api=query")
            },

            detail(key) {
                if(this.serialize){
                    let data = {
                        host: this.serializeUrl+key.value
                    }
                    http.redisKeyDetailAndSerialize(data, "RedisConsole.vue?api=redisKeyDetailAndSerialize");
                }else{
                    let data = {
                        token: this.$token,
                        key: key.value
                    };
                    http.redisKeyDetail(data, "RedisConsole.vue?api=getByKey")
                }
            },

            jsonFormat(str) {
                try {
                    let newData = JSON.stringify(JSON.parse(str), null, 2);
                    return newData;
                } catch (e) {
                    console.log(e)
                }
                return str;
            },

            runCmd() {
              let s = this.$getSelectText();
                let cmd_ = s ? s.trim() : document.getElementById("redis_cmd").innerText.trim();
                this.cmd = cmd_;
                if(this.cmd == null || this.cmd.trim() == ''){
                    return ;
                }
                let data = {
                    cmd:this.cmd,
                    uuid:this.$token
                }
                http.redisCmdLine(data, "RedisConsole.vue?api=redisCmdLine")
            },

            parentChange(parent) {
                //  影响所有子节点的选中状态
                parent.array.forEach(k => {
                    k.select = parent.select
                })

                parent.indeterminate = false;
            },

            childChange(parent, child) {
                //  统计选中和补选中的数量
                let select_ = 0;
                let unselect_ = 0;
                parent.array.forEach(k => {
                    if (k.select) {
                        select_++;
                    } else {
                        unselect_++;
                    }
                })

                if (select_ == 0) {
                    parent.select = false;
                    parent.indeterminate = false;
                } else if (unselect_ == 0) {
                    parent.select = true;
                    parent.indeterminate = false;
                } else {
                    parent.indeterminate = true;
                    parent.select = false;
                }
            },
            delete0(){
                if(this.keys == null){
                    return ;
                }

                let delArray = [];
                for(let x in this.keys){
                    for(let y of this.keys[x].array){
                       if(y.select){
                         delArray.push(y.value);

                       }
                    }
                }

                if(delArray.length > 0){
                  let data = {
                    cmd:"del "+delArray.join(" "),
                    uuid:this.$token
                  }
                  http.redisCmdLine(data, "RedisConsole.vue?api=redisCmdLine")
                }
            },

            reload0(){
                this.query();
            },

          saveConfig(){
            let parse = {};
            parse.jsonFormat_ = this.jsonFormat_;
            parse.serialize = this.serialize;
            parse.serializeUrl = this.serializeUrl;
            parse.host = this.host;
            parse.port = this.port;
            parse.password = this.password;
            parse.showChild_ = this.showChild_;

            this.$cache.putCommon("redis_console",JSON.stringify(parse))
          }
        },

        destroyed() {
            this.$event.unregister("RedisConsole.vue");
            //  保存配置信息
            this.saveConfig();
            console.log("destroy")
        }
    }
</script>


<style>
    .input_box {
        border : 2px solid #dcdfe6;
        display: block;
        height: 100%;
        padding: 8px;
        overflow: scroll;
        box-sizing: border-box;
    }

    .input_box:focus {
        border: 2px solid #409eff
    }

    .input_box::-webkit-scrollbar{
        display: none;
    }

    .common_box {
        border: 2px solid #67c23a;
        display: block;
        height: 100%;
        box-sizing: border-box;
    }

    .no_bar {
        display: block;
    }

    .no_bar::-webkit-scrollbar {
        display: none;
    }

    pre{
        white-space:pre-wrap;
        white-space:-moz-pre-wrap;
        white-space:-pre-wrap;
        white-space:-o-pre-wrap;
        word-wrap:break-word;
        overflow-y: scroll;
        user-select: text;

    }

    pre::-webkit-scrollbar{
        display: none;
    }

    .select_01 {

    }

    .select_01 :hover {
        color: #409eff;
    }

    .select_02 {
        color: #409eff;
    }
</style>